/**
 * 日志数据库写入中间件
 * 自动将所有日志写入数据库
 */
const db = require('../config/database');

class DatabaseLogger {
  constructor() {
    this.queue = [];
    this.isProcessing = false;
    this.batchSize = 50;
    this.flushInterval = 5000; // 5秒刷新一次
    
    // 启动定时刷新
    setInterval(() => this.flush(), this.flushInterval);
  }

  /**
   * 添加系统日志到队列
   */
  addSystemLog(level, action, content, options = {}) {
    const {
      userId = 0,
      userType = 'system',
      ipAddress = null,
      userAgent = null
    } = options;

    this.queue.push({
      type: 'system',
      level,
      action,
      content,
      userId,
      userType,
      ipAddress,
      userAgent,
      timestamp: new Date()
    });

    // 队列满了立即刷新
    if (this.queue.length >= this.batchSize) {
      this.flush();
    }
  }

  /**
   * 添加客户端日志到队列
   */
  addClientLog(userId, clientId, level, message, stackTrace = null, clientTime = null) {
    this.queue.push({
      type: 'client',
      userId,
      clientId,
      level,
      message,
      stackTrace,
      clientTime: clientTime || new Date(),
      timestamp: new Date()
    });

    // 队列满了立即刷新
    if (this.queue.length >= this.batchSize) {
      this.flush();
    }
  }

  /**
   * 刷新队列到数据库
   */
  async flush() {
    if (this.isProcessing || this.queue.length === 0) {
      return;
    }

    this.isProcessing = true;
    const logsToWrite = [...this.queue];
    this.queue = [];

    try {
      // 分组处理系统日志和客户端日志
      const systemLogs = logsToWrite.filter(log => log.type === 'system');
      const clientLogs = logsToWrite.filter(log => log.type === 'client');

      // 批量插入系统日志
      if (systemLogs.length > 0) {
        const systemValues = systemLogs.map(log => [
          log.userId,
          log.userType,
          log.level,
          log.action,
          log.content,
          log.ipAddress,
          log.userAgent,
          log.timestamp
        ]);

        await db.query(
          `INSERT INTO system_logs (user_id, user_type, level, action, content, ip_address, user_agent, created_at)
           VALUES ?`,
          [systemValues]
        );

        console.log(`✅ 写入 ${systemLogs.length} 条系统日志到数据库`);
      }

      // 批量插入客户端日志
      if (clientLogs.length > 0) {
        const clientValues = clientLogs.map(log => [
          log.userId,
          log.clientId,
          log.level,
          log.message,
          log.stackTrace,
          log.clientTime,
          log.timestamp
        ]);

        await db.query(
          `INSERT INTO client_logs (user_id, client_id, level, message, stack_trace, client_time, received_at)
           VALUES ?`,
          [clientValues]
        );

        console.log(`✅ 写入 ${clientLogs.length} 条客户端日志到数据库`);
      }
    } catch (error) {
      console.error('❌ 写入日志到数据库失败:', error);
      // 失败的日志放回队列
      this.queue.unshift(...logsToWrite);
    } finally {
      this.isProcessing = false;
    }
  }

  /**
   * 关闭时刷新所有日志
   */
  async close() {
    await this.flush();
  }
}

// 创建单例
const dbLogger = new DatabaseLogger();

// 进程退出时刷新日志
process.on('beforeExit', async () => {
  await dbLogger.close();
});

process.on('SIGINT', async () => {
  await dbLogger.close();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  await dbLogger.close();
  process.exit(0);
});

module.exports = dbLogger;
